global target
################################################################################
#  proc uboot_env: Convert u-boot variables in a string ready to be flashed
#                  in the region reserved for environment variables
################################################################################
proc set_uboot_env {nameOfLstOfVar} {
    upvar $nameOfLstOfVar lstOfVar
    
    # sector size is the size defined in u-boot CFG_ENV_SIZE
    set sectorSize [expr 0x1000 - 4]

    set strEnv [join $lstOfVar "\0"]
    while {[string length $strEnv] < $sectorSize} {
        append strEnv "\0"
    }
    set strCrc [binary format i [::vfs::crc $strEnv]]
    return "$strCrc$strEnv"
}

################################################################################
#  Main script: Load the linux demo in DataFlash,
#               Update the environment variables
################################################################################
set bootstrapFile	"dataflash_at91sam9263ek.bin"
set ubootFile	"u-boot.bin"	
set kernelFile	"uImage.bin"
set ubootEnvFile	"u-boot.env"

## DataFlash Mapping
set baseAddr		0xC0000000
set bootStrapAddr	0x00000000
set ubootAddr	0x00008000
set ubootEnvAddr   0x00004200
set kernelAddr	0x00042000

# u-boot variable
set kernelUbootAddr [format "0x%08X" [expr $baseAddr + $kernelAddr]]
set kernelLoadAddr	0x22200000


## NandFlash Mapping
set kernelSize	[format "0x%08X" [file size $kernelFile]]

lappend u_boot_variables \
    "ethaddr=3a:1f:34:08:54:54" \
    "ipaddr=192.168.0.7" \
    "bootdelay=1" \
    "baudrate=115200" \
    "stdin=serial" \
    "stdout=serial" \
    "stderr=serial" \
    "bootargs=mem=64M console=ttyS0,115200 root=/dev/mtdblock1 rw rootfstype=jffs2 init=/sbin/init" \
    "bootcmd=cp.b $kernelUbootAddr $kernelLoadAddr $kernelSize; bootm $kernelLoadAddr"

puts "-I- === Initialize the DataFlash access ==="
DATAFLASH::SelectDataflash AT91C_SPI0_CS0

puts "-I- === Erase all the DataFlash blocs and test the erasing ==="
DATAFLASH::EraseAllDataFlash

puts "-I- === Load the bootstrap: dataflash_at91sam9263ek in the first sector ==="
DATAFLASH::SendBootFile $bootstrapFile

puts "-I- === Load the u-boot in the next sectors ==="
send_file {DataFlash AT45DB/DCB} "$ubootFile" $ubootAddr 0 

puts "-I- === Load the u-boot environment variables ==="
set fh [open "$ubootEnvFile" w]
fconfigure $fh -translation binary
puts -nonewline $fh [set_uboot_env u_boot_variables]
close $fh
send_file {DataFlash AT45DB/DCB} "$ubootEnvFile" $ubootEnvAddr 0 

puts "-I- === Load the Kernel image ==="
send_file {DataFlash AT45DB/DCB} "$kernelFile" $kernelAddr 0
